<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\cache\driver\Redis;
class Menu extends Auth
{

	public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->getChildIDdata = [];
    }


    // 侧边栏列表
    public function list(Request $request){
        
        // 按菜单名查找条件
        if(isset($this->data['searchText']) && $this->data['searchText']){
            $where['mu.content'] = ['like', '%' . trim($this->data['searchText']) . '%'];
            // $where['mu.content'] = ['like', '%部门%'];
            $returnData['searchText'] = $this->data['searchText'];
        }else{
            $returnData['searchText'] = '';
        }
        // 按控制器查找条件
        if(isset($this->data['control']) && $this->data['control']){
            $where['zu.control'] = trim($this->data['control']);
            $returnData['control'] = $this->data['control'];
        }else{
            $returnData['control'] = '';
        }
        $where['mu.lang'] = $this->lang;
        // vue获取数据，所以浏览器直接打开直接跳转页面由VUE获取数据遍历
        if($request->isAjax()){
            $menuList = getSearch('menu','zu',['zu.*,mu.content'],$where,[['multi_lang mu','zu.mkey = mu.mkey']],'zu.drank asc');
            // 按条件搜索时不用进行level比较
            if(count($where) == 1){
                $menuList = getTree($menuList);
            }
            
            foreach ($menuList as $k => $v) {
                if(count($where) > 1){
                    $menuList[$k]['level'] = 0;
                    $menuList[$k]['child'] = 0;
                }else{
                    $menuList[$k]['child'] = Db::name('menu')->where('pid',$v['id'])->count();
                }
                $menuList[$k]['is_menu'] = $menuList[$k]['is_menu'] == 1 ? 'O' : '-';
                $menuList[$k]['is_disable'] = $menuList[$k]['disable'] == 1 ?  'O' : '-';
                $menuList[$k]['control'] = $menuList[$k]['control'] != '' ?  $menuList[$k]['control'] : '-';
                $menuList[$k]['option'] = $menuList[$k]['option'] != '' ?  $menuList[$k]['option'] : '-';
                $menuList[$k]['style'] = $menuList[$k]['style'] != '' ?  $menuList[$k]['style'] : '-';
            }
            // 获取分页数据
            $returnData['size'] = count( $menuList);
            if(isset($this->data['page']) && isset($this->data['limit'])){
                if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                    $menuList = array_slice($menuList,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                    $returnData['page'] = $this->data['page'];
                }
            }
            $returnData['menuList'] = $menuList;
            // dump($returnData);die;
            return json_encode($returnData);
        }else{
            return view('menu');
        }
    }


    // 侧边栏新增
    public function insert($data){
    	if(isset($data['zh']['name']) && $data['zh']['name']){
            $where['mu.lang'] = $this->lang;
            $where['mu.content'] = $data['zh']['name'];
            $where['zu.pid'] = isset($data['zh']['pid']) ? $data['zh']['pid'] : 0;
            $result = getSearch('menu','zu',['zu.id'],$where,[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id asc');
            if (empty($result)) {    // 验证菜单名称在当前pid下是否已存在
                $menuData['pid'] = isset($data['zh']['pid']) ? $data['zh']['pid'] : 0;
                $menuData['control'] =trim(strtolower($data['zh']['control']));
                $menuData['option'] = trim(strtolower($data['zh']['option']));
                $menuData['is_menu'] = $data['zh']['is_menu'];
                $menuData['style'] = $data['zh']['style'];
                $menuData['drank'] = $data['zh']['drank'];
                $menuData['disable'] = $data['zh']['disable'];
                $menuData['create_at'] = time();
                $menuData['drank'] = $data['zh']['drank'] !='' ? $data['zh']['drank'] :(hasData('menu',['pid'=>$menuData['pid']])+1);
                $whereDrank = 'drank between '.($data['zh']['drank']).' and 99';
                $is_drank = changeDrank('menu',['pid'=>$menuData['pid']],$whereDrank);
                // return $menuData;
                // 开启事务
                Db::startTrans();   
                    $res = Db::name('menu')->insertGetId($menuData);
                    if($res){
                        $mkey ="menu_".$res;
                        $res = Db::name('menu')->where('id',$res)->update(['mkey'=>$mkey]);
                        $lang_cate = getLanguage();
                        foreach ($lang_cate as $k => $v) {
                            $insertData['mkey'] = $mkey;
                            $insertData['lang'] = $v['code'];
                            $insertData['content'] = $data['zh']['name'];
                            
                            $ress = Db::name('multi_lang')->insert($insertData);
                        }
                        if($ress){
                            //提交事务
                            Db::commit();
                            return  json_encode(array('status' => 1,'msg'=>lang('method').'：'.$data['zh']['name'].','.lang('added_successfully') ));
                        }else{
                            return  json_encode(array('status' => 0,'msg'=>lang('method').'：'.$data['zh']['name'].','.lang('add_failed')));
                        }
                    }else{
                        return  json_encode(array('status' => 0,'msg'=>lang('method').'：'.$data['zh']['name'].','.lang('add_failed') ));
                    }
            }else{
                return  json_encode(array('status' => 3,'msg'=>lang('method').'：'.$data['zh']['name'].','.lang('already_exists') ));
            }
    	}else{
            return  json_encode(array('status' => 2,'msg'=>lang('missing').' '.lang('method') ));
        }
        
    }


    public function addopen(){
        if($this->data['request'] == 'insert'){
            // return $this->data;
            $res = $this->insert($this->data);
            return $res;
        }else{
            if(isset($this->data['id']) && $this->data['id']){
                $res = getMultiLangName('menu',['*'],['id'=>$this->data['id']],'id asc');
                $title = lang('addsub');
            }else{
                $res = [];
                $title = lang('addfunc');
            }
            // dump($res);die;
            return view('menuopen',['allParent'=>$res,'title'=>$title,'request'=>'add']);
        }
    }

    // 获取当前类行下 所以能用的子级
    function getChildID($table,$field,$where,$pid=0)
    {   
        $_data = Db::name($table)
                    ->field($field)
                    ->where($where)
                    ->where('pid',$pid)
                    // ->fetchSql()
                    ->select();
                // return $_data;
        if(!empty( $_data)){
            foreach ($_data as $k => $v) {
                array_push($this->getChildIDdata,$v['id']);
                $res = $this->getChildID($table,$field,$where,$v['id']);
            }
        }
            return $this->getChildIDdata;
    }

    public function editopen(){
        if($this->data['request'] == 'update'){
            unset($this->data['request']);
            foreach ($this->data as $k => $v) {
                if($v['id'] == $v['pid']){
                    return json_encode(array('status'=>2,'msg'=>'所属功能选择有误，所属功能不能为自己'));
                }
                $pid = $this->getChildID('menu',['id'],'1=1',$v['id']);
                if( in_array($v['pid'], $pid)){
                    return json_encode(array('status'=>2,'msg'=>'所属功能选择有误，为当前功能的子级'));
                }
                if($v['name'] == ''){
                    return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
                }else{
                    $menuMulti[$k]['lang'] = $k;
                    $menuMulti[$k]['content'] = $v['name'];
                    $menuMulti[$k]['mkey'] = 'menu_'.$v['id'];
                    unset($this->data[$k]['name']);
                }
            }
            // 开启事务
            Db::startTrans();   
            try{

                if($this->data['zh']['drank'] > $this->data['zh']['olddrank']){  
                    $whereDrank = 'drank between '.$this->data['zh']['drank'].' and 99';
                }

                if($this->data['zh']['drank'] < $this->data['zh']['olddrank']){
                    $whereDrank = 'drank between '.$this->data['zh']['drank'].' and '.($this->data['zh']['olddrank']-1);
                }
                // return $whereDrank;
                // 是否需要从新排序
                if($this->data['zh']['drank'] != $this->data['zh']['olddrank']){
                    $is_drank = changeDrank('menu',['pid'=>$this->data['zh']['pid']],$whereDrank);
                }
            
                unset($this->data['zh']['olddrank']);

                
                $this->data['zh']['control'] = trim(strtolower($this->data['zh']['control']));
                $this->data['zh']['option'] = trim(strtolower($this->data['zh']['option']));
                // return $this->data['zh'];
                $res = Db::name('menu')->where('id',$this->data['zh']['id'])->update($this->data['zh']);
                // return $res;
                if($res >= 0){
                    foreach ($menuMulti as $k1 => $v1) {
                        if($v1['lang'] == $this->lang){
                            $content = $v1['content'];
                        }
                        // return $v1;
                        $ress = updateData('multi_lang',['lang'=>$v1['lang'],'mkey'=>$v1['mkey']],['content'=>$v1['content']]);
                    }
                    
                    if($ress >= 0){
                        //提交事务
                        Db::commit();
                        return  json_encode(array('status' => 1,'msg'=>lang('proattr').$content.' '.lang('edited_successfully') ));
                    }else{
                        return  json_encode(array('status' => 0,'msg'=>lang('proattr').$content.' '.lang('edit_failed') ));
                    }
                }else{
                    return  json_encode(array('status' => 0,'msg'=>lang('proattr').' '.lang('edit_failed') ));
                }
            } catch (\Exception $e) {
                //回滚事务
                Db::rollback();
                return  json_encode(array('status' => 0,'msg'=>lang('edit_failed') ));
            }
        }else{
            $allParent = getMultiLangName('menu',['*'],'1= 1','id asc');
            $allParent = getTree($allParent);
            foreach ($allParent as $k => $v) {
                $allParent[$k]['child'] = 1;
            }
            $info = getMultiLangName('menu',['*'],['id'=>$this->data['id']],'id asc')[0];
            // dump($info);die;
            return view('menuopen',['allParent'=>$allParent,'info'=>$info,'pid'=>$this->data['pid'],'threeLevel'=>$this->data['id'],'title'=>lang('edit'),'request'=>'edit']);
        }
    }

    // 侧边栏状态
    public function updateStatus(){
        if($this->data['id']){
            $is_del = Db::name('menu')->where('pid',$this->data['id'])->find();
            $notic = $this->data['disable'] == 1 ? lang('locking') : lang('unlock');
            if(!$is_del){
                $res = Db::name('menu')->where('id',$this->data['id'])->update(['disable'=>$this->data['disable']]);
                if($res){
                    return json_encode(array('status' => 1,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.$notic.' '.lang('successfully') ));
                }else{
                    return  json_encode(array('status' => 0,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.$notic.' '.lang('failed') ));
                }
            }else{
                return  json_encode(array('status' => 0,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.lang('already_exists').' '.$notic.' '.lang('failed')));
            }
        }else{
            return json_encode(array('status' => 2,'msg'=>lang('improve_submission_data') ));
        }
    }

     // 删除侧边栏
    public function requestDelete(){
        if($this->data['id']){
            $is_del = hasData('menu',['pid'=>$this->data['id']]);
            if(!$is_del){
                $content = getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content');
                $res = deleteData('menu',['id'=>$this->data['id']]);
                if($res){
                    $res1 = deleteData('multi_lang',['mkey'=>'menu_'.$this->data['id']]);
                    return json_encode(array('status' => 1,'msg'=>$content.' '.lang('cleared_successfully') ));
                }else{
                    return  json_encode(array('status' => 0,'msg'=>$content.' '.lang('clear_failed') ));
                }
            }else{
                return  json_encode(array('status' => 0,'msg'=>$content.' '.lang('clear_failed') ));
            }
        }else{
            return json_encode(array('status' => 2,'msg'=>lang('improve_submission_data')));
        }
    }

}
